/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * 非递归 栈的思想
 * @param {TreeNode} root
 * @return {TreeNode}
 */
 var invertTree = function(root) {
    let stack = []
    if(!root) return root
    stack.push(root)
    while(stack.length){
        let node = stack.pop()
        if(node!==null){
            node.right&&stack.push(node.right)
            node.left&&stack.push(node.left)
            stack.push(node)
            stack.push(null)
        }else{
            node = stack.pop()
            swap(node,node.left,node.right)
        }
        
    }

    function swap(root,left,right){
        let team = left
        left = right
        right = team
        root.left = left
        root.right = right
    }
};

/**
 * 递归思想
 * @param {*} root 
 */
 var invertTree = function(root) {
    if(root==null) return root
    if(root!==null){
        let team = root.left
        root.left = root.right
        root.right = team
        invertTree(root.left)
        invertTree(root.right)
        return root
    }
};